package captcha

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wenlng/go-captcha/v2/click"
	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"
	"product/common/validator"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckClickCaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 验证验证码
func NewCheckClickCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckClickCaptchaLogic {
	return &CheckClickCaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckClickCaptchaLogic) CheckClickCaptcha(req *types.ClickCaptchaCheckReq) (resp *types.ClickCaptchaCheckResp, err error) {
	valid, err := validClickCaptchaInput(req)
	if !valid {
		return nil, err
	}
	cachedDots, err := l.svcCtx.Redis.GetCtx(l.ctx, req.CaptchaKey)
	if err != nil || validator.IsEmptyString(cachedDots) {
		return &types.ClickCaptchaCheckResp{Ok: false}, err
	}
	var dotMap map[int]*click.Dot
	err = json.Unmarshal([]byte(cachedDots), &dotMap)
	if err != nil {
		return &types.ClickCaptchaCheckResp{Ok: false}, errors.New("验证码数据解析失败")
	}
	dotMapLen := len(dotMap)
	if (dotMapLen) != len(req.CaptchaDots) {
		return &types.ClickCaptchaCheckResp{Ok: false}, errors.New("验证码数据错误")
	}
	for i := 0; i < dotMapLen; i++ {
		dot := dotMap[i]
		rDot := req.CaptchaDots[i]
		checkResult := click.CheckPoint(int64(rDot.X), int64(rDot.Y), int64(dot.X), int64(dot.Y), int64(dot.Width), int64(dot.Height), 0)
		if !checkResult {
			return &types.ClickCaptchaCheckResp{Ok: false}, errors.New("验证码错误")
		}
	}

	return &types.ClickCaptchaCheckResp{Ok: true}, nil
}

func validClickCaptchaInput(req *types.ClickCaptchaCheckReq) (bool, error) {
	if validator.IsEmptyString(req.CaptchaKey) {
		return false, errors.New("captchaKey不能为空")
	}
	if len(req.CaptchaDots) == 0 {
		return false, errors.New("captchaDots不能为空")
	}
	return true, nil
}
